
import json
import os

import openai
import requests

openai.api_key = os.environ["OPENAI_API_KEY_ZHIHU"]
openai.api_base= os.environ["OPENAI_API_BASE_ZHIHU"]


# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
amap_key = "6d672e6194caa3b639fccf2caf06c342"

tools = [{
        "type": "function",
        "function": {
            "name": "get_location_coordinate",
            "description": "根据POI名称，获得POI的经纬度坐标",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "POI名称，必须是中文",
                    },
                    "city": {
                        "type": "string",
                        "description": "POI所在的城市名，必须是中文",
                    }
                },
                "required": ["location", "city"],
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_nearby_pois",
            "description": "搜索给定坐标附近的poi",
            "parameters": {
                "type": "object",
                "properties": {
                    "longitude": {
                        "type": "string",
                        "description": "中心点的经度",
                    },
                    "latitude": {
                        "type": "string",
                        "description": "中心点的纬度",
                    },
                    "keyword": {
                        "type": "string",
                        "description": "目标poi的关键字",
                    }
                },
                "required": ["longitude", "latitude", "keyword"],
            }
        }
    }]

def get_location_coordinate(location, city):
    url = f"https://restapi.amap.com/v5/place/text?key={amap_key}&keywords={location}&region={city}"
    print(url)
    r = requests.get(url)
    result = r.json()
    if "pois" in result and result["pois"]:
        return result["pois"][0]
    return None


def search_nearby_pois(longitude, latitude, keyword):
    url = f"https://restapi.amap.com/v5/place/around?key={amap_key}&keywords={keyword}&location={longitude},{latitude}"
    print(url)
    r = requests.get(url)
    result = r.json()
    ans = ""
    if "pois" in result and result["pois"]:
        for i in range(min(3, len(result["pois"]))):
            name = result["pois"][i]["name"]
            address = result["pois"][i]["address"]
            distance = result["pois"][i]["distance"]
            ans += f"{name}\n{address}\n距离：{distance}米\n\n"
    return ans

def getChatResponse(messages,model="gpt-3.5-turbo"):
    # Step 1: send the conversation and available functions to the model
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,
        seed=1024,  # 随机种子保持不变，temperature 和 prompt 不变的情况下，输出就会不变
        tool_choice="auto",  # 默认值，由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数，详见官方文档
        tools=tools,
    )
    return response

def run_conversation(userInput,model="gpt-3.5-turbo"):
    messages = [{"role": "system", "content": "你是一个地图通，你可以找到任何地址。"},
                {"role": "system", "content": userInput}]

    response = getChatResponse(messages,model)
    response_message = response.choices[0].message
    tool_calls = response_message.tool_calls
    result_response = response
    # Step 2: check if the model wanted to call a function
    while tool_calls:
        # Step 3: call the function
        # Note: the JSON response may not always be valid; be sure to handle errors
        available_functions = {
            "get_location_coordinate": get_location_coordinate,
            "search_nearby_pois":search_nearby_pois
        }  # only one function in this example, but you can have multiple
        messages.append(result_response.choices[0].message)  # extend conversation with assistant's reply
        # Step 4: send the info for each function call and function response to the model
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = json.loads(tool_call.function.arguments)
            function_response = function_to_call(**function_args)
            messages.append(
                {
                    "tool_call_id": tool_call.id,
                    "role": "tool",
                    "name": function_name,
                    "content": str(function_response),
                }
            )  # extend conversation with function response
        second_response = getChatResponse(messages, model)
        #判断是否 second_response.choices[0].message 有tool_calls属性

        if "tool_calls" in second_response.choices[0].message:
            tool_calls = second_response.choices[0].message.tool_calls
        else:
            tool_calls = None

        result_response = second_response

    return result_response

result_response = run_conversation("我想在北京五道口附近喝咖啡，给我推荐几个")
print(result_response.choices[0].message.content)